package com.hntxk.cqzd.consultation.service.impl;


import com.hntxk.core.framework.model.ResultModel;
import com.hntxk.core.framework.service.impl.BaseServiceImpl;
import com.hntxk.core.util.DateUtil;
import com.hntxk.cqzd.common.service.CommonFileService;
import com.hntxk.cqzd.consultation.entity.TblDibEmp;
import com.hntxk.cqzd.consultation.entity.TblDibFile;
import com.hntxk.cqzd.consultation.entity.TblDibInfo;
import com.hntxk.cqzd.consultation.model.DibAndDiacModel;
import com.hntxk.cqzd.consultation.model.DibAndEmpModel;
import com.hntxk.cqzd.consultation.service.DibEmpService;
import com.hntxk.cqzd.consultation.service.DibFileService;
import com.hntxk.cqzd.consultation.service.DibInfoService;
import com.hntxk.cqzd.diacrisis.entity.TblDiacrisisInfo;
import com.hntxk.cqzd.diacrisis.service.DiacrisisInfoService;
import com.hntxk.sp.dict.service.IDictService;
import com.hntxk.sp.log.model.ActionLog;
import com.hntxk.sp.log.model.ActionType;
import com.hntxk.sp.util.LogRecordUtil;
import com.hntxk.sp.util.LoginUserUtil;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ClassUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @author <a href="huangbiquan@hotmail.com">Huang.Biquan</a>
 * @Description: 会诊信息接口实现类 <br>
 * @Project: SP <br>
 * @date 2019/6/3 10:01 <br>
 */
@Component("dibInfoManageService")
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class DibInfoServiceImpl extends BaseServiceImpl<TblDibInfo> implements DibInfoService {


    final DiacrisisInfoService diacrisisService;
    private TblDiacrisisInfo tblDiacrisisInfo;
    final DibEmpService dibEmpService;

    @Autowired
    @Qualifier("commonFileServiceImpl")
    CommonFileService commonFileService;

    @Autowired
    @Qualifier("dibFileManageService")
    DibFileService dibFileService;


    @Autowired
    @Qualifier("dictService")
    IDictService dictService;



    public static String DIBINFO_MAPPER_NAMESPACE = "com.hntxk.cqzd.consultation.mapper.DibInfoMapper.";

    public DibInfoServiceImpl(@Qualifier("dibEmpManageService") DibEmpService dibEmpService, @Qualifier("diacInfoService") DiacrisisInfoService diacrisisService) {
        super(DIBINFO_MAPPER_NAMESPACE);
        this.dibEmpService=dibEmpService;
        this.diacrisisService = diacrisisService;
    }


    //新增会诊信息
    @Override
    public ResultModel<DibAndEmpModel> insert(DibAndEmpModel dibAndEmpModel, MultipartFile[] files) throws IOException {
        DibAndDiacModel dibAndDiacModel = dibAndEmpModel.getDibAndDiacModel();
        getPrimaryKey(dibAndDiacModel);
        dibAndDiacModel.setCreateTime(new Date());
        dibAndDiacModel.setCreateUserId(LoginUserUtil.getLoginOperatorIdLong());
        dibAndDiacModel.setCreateUserName(LoginUserUtil.getLoginUserName());
        //新增会诊信息
        insert(DIBINFO_MAPPER_NAMESPACE+"insert",dibAndDiacModel);
        if(dibAndEmpModel.getDibEmp().size()>0){
            dibEmpService.insert(dibAndEmpModel);
        }
        if(files!=null&&files.length>0){
            //调用上传文件的方法
            commonFileService.upload( DibFileServiceImpl.DIBFILE_MAPPER_NAMESPACE+"insert",files,dibAndDiacModel.getDibId(),"dib");
        }
            //记录日志
        tblDiacrisisInfo= diacrisisService.getById(dibAndDiacModel.getDiacrisisId());
            Long aLong = LogRecordUtil.addLog(new ActionLog(TblDibInfo.class, dibAndDiacModel.getDibId() + "", "12",
                    ActionType.ADD, "新增会诊信息：" + dibAndDiacModel.getDibId() + "[ " + tblDiacrisisInfo.getPatientName() + " ]"));
        return ResultModel.empty();

    }

    @Override
    public ResultModel<DibAndEmpModel> update(DibAndEmpModel dibAndEmpModel, MultipartFile[] files) throws IOException{
        DibAndDiacModel dibAndDiacModel=dibAndEmpModel.getDibAndDiacModel();
        getPrimaryKey(dibAndDiacModel);
        dibAndDiacModel.setUpdateTime(new Date());
        dibAndDiacModel.setUpdateUserId(LoginUserUtil.getLoginOperatorIdLong());
        dibAndDiacModel.setUpdateUserName(LoginUserUtil.getLoginUserName());
        int num = update(DIBINFO_MAPPER_NAMESPACE + "update", dibAndEmpModel.getDibAndDiacModel());
        if(files!=null&&files.length>0){
            //调用上传文件的方法
            commonFileService.upload( DibFileServiceImpl.DIBFILE_MAPPER_NAMESPACE+"insert",files,dibAndDiacModel.getDibId(),"dib");
        }
        if(dibAndEmpModel.getDibEmp()!=null&&!dibAndEmpModel.getDibEmp().isEmpty()){
            dibEmpService.update(dibAndEmpModel);

        }
        LogRecordUtil.addLog(new ActionLog(TblDiacrisisInfo.class, dibAndEmpModel.getDibAndDiacModel().getDibId() + "", "12",
                ActionType.UPDATE, "修改了会诊信息：" + dibAndEmpModel.getDibAndDiacModel().getDibId() + "[ " + dibAndEmpModel.getDibAndDiacModel().getDibTitle() + " ]"));
        return ResultModel.empty();
    }

    @Override
    public DibAndEmpModel getById(Long id) {
        DibAndEmpModel dibAndEmpModel=new DibAndEmpModel();
        dibAndEmpModel.setDibAndDiacModel(get(DIBINFO_MAPPER_NAMESPACE+"get",id));
        dibAndEmpModel.setDibEmp(dibEmpService.getByFkId(id));
        dibAndEmpModel.setDibFiles(dibFileService.getByFkId(id));
        return dibAndEmpModel;
    }



    @Override
    public DibAndEmpModel getDibInfo(Long infoId) {

        //查询会诊信息
        DibAndDiacModel dibAndDiacModel = get(DIBINFO_MAPPER_NAMESPACE+"get",infoId);
        DibAndEmpModel model = new DibAndEmpModel();
        model.setDibAndDiacModel(dibAndDiacModel);
        //查询从表数据
        List<TblDibEmp> tblDibEmps = dibEmpService.getByFkId(infoId);
        model.setDibEmp(tblDibEmps);

        return model;
    }

    @Override
    public List<DibAndEmpModel> getByFkId(Long id) {
        TblDibInfo tblDibInfo=new TblDibInfo();
        List<DibAndEmpModel> dibAndEmpModels=new ArrayList<>();
        tblDibInfo.setDiacrisisId(id);
        List<DibAndDiacModel> dibAndDiacModels = (List<DibAndDiacModel>) query(DIBINFO_MAPPER_NAMESPACE + "getByFkId", tblDibInfo);

        if(dibAndDiacModels.size()>0) {
            for (DibAndDiacModel dibAndDiacModel : dibAndDiacModels) {
                DibAndEmpModel dibAndEmpModel=new DibAndEmpModel();
                dibAndEmpModel.setDibAndDiacModel(dibAndDiacModel);
                List<TblDibFile>  dibFiles= dibFileService.getByFkId(dibAndDiacModel.getDibId());
                List<TblDibEmp> emps = dibEmpService.getByFkId(dibAndDiacModel.getDibId());
                dibAndEmpModel.setDibFiles(dibFiles);
                dibAndEmpModel.setDibEmp(emps);
                dibAndEmpModels.add(dibAndEmpModel);
            }
        }
        return dibAndEmpModels;
    }
    @Override
    public ResponseEntity<byte[]> exportPdf(DibAndEmpModel dibAndEmpModel) {



        // 模板路径
        String templatePath = "C:/ruanjian/model.pdf";
        PdfReader reader;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        try {
            InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("static/cqzd/js/model.pdf");
//            String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
//            String pdfPath = path+"static/cqzd/js/model.pdf";
            reader = new PdfReader(resourceAsStream);// 读取pdf模板
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();
            DibAndDiacModel dibAndDiacModel = dibAndEmpModel.getDibAndDiacModel();
            List<TblDibEmp> dibEmp = dibAndEmpModel.getDibEmp();
            String attendees="";//参会人员
            String absence ="";//缺席人员
            for (int i = 0; i <dibEmp.size() ; i++) {
                TblDibEmp tblDibEmp = dibEmp.get(i);
                Character isAbsence = tblDibEmp.getIsAbsence();
                if(isAbsence=='1'){
                    attendees+=tblDibEmp.getEmpName()+",";
                }else{
                    absence+=tblDibEmp.getEmpName()+",";
                }
            }
            attendees=attendees.substring(0,attendees.length()-1);
            absence=absence.substring(0,absence.length()-1);
            Map<String,String> map=new HashMap();
            map.put("title",dibAndDiacModel.getDibTitle()); //主题
            map.put("dibAddr",dibAndDiacModel.getDibAddress());//会诊地址
            map.put("attendees",attendees);//参会人员
            map.put("absence",absence);//缺席人员
            map.put("name",dibAndDiacModel.getPatientName());//患者姓名
            map.put("emcee",dibAndDiacModel.getDibEmcee());//主持人
            map.put("recorder",dibAndDiacModel.getDibRecorder());//记录人
            map.put("dibtime", DateUtil.getStrByFormat(dibAndDiacModel.getDibTime(),"yyyy-MM-dd"));//会诊时间
            map.put("purpose",dibAndDiacModel.getDibPurpose());//会诊目标
            map.put("current",dibAndDiacModel.getDibCurrent());//目前诊断
            map.put("feature",dibAndDiacModel.getDibFeature());//病史特征
            map.put("consult",dibAndDiacModel.getDibConsult());//产科咨询
            map.put("transport",dibAndDiacModel.getDibTransport());//转运流程
            map.put("propose",dibAndDiacModel.getDibPropose());//会诊意见
            map.put("other",dibAndDiacModel.getDibOther());//其他
            for (String key : map.keySet()) {
                String value = map.get(key);
                form.setField(key, value); // 为字段赋值,注意字段名称是区分大小写
            }
            /* 使用中文字体 */
            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
            fontList.add(bf);
            AcroFields acroFields = stamper.getAcroFields();
            acroFields.setSubstitutionFonts(fontList); //设置字体 解决中文数据显示不全问题
            stamper.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑，一定要设为true
            stamper.close();
            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, bos);
            doc.open();
            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage);
            doc.close();
            return ResponseEntity.of(Optional.of(bos.toByteArray()));
        } catch (IOException e) {
            System.out.println(1);
        } catch (DocumentException e) {
            System.out.println(2);
        }
        return null;
    }



}
